import { LoadingOutlined } from '@ant-design/icons'
import { ConfigProvider, message } from 'antd'
import zhCN from 'antd/locale/zh_CN'
import axios from 'axios'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import duration from 'dayjs/plugin/duration'
import updateLocale from 'dayjs/plugin/updateLocale'
import dva from 'dva'
import createLoading from 'dva-loading'
import ReactDOM from 'react-dom/client'

import { modal, theme } from '@/utils/antdHelper'
import config from '@/utils/config'
import dvaEffectsEnhancer from '@/utils/dvaUtil/dvaEffectsEnhancer'
import onAppError from '@/utils/onAppError'

import appModel from './models/app'
import noticeModel from './models/app/notice'
import Router from './Router'

import 'virtual:uno.css'
import './index.less'

const { apiUrlPrefix } = config

dayjs.locale('zh-cn')
dayjs.extend(updateLocale)
dayjs.extend(duration)
dayjs.updateLocale('zh-cn', {
  weekStart: 0,
})

message.config({
  top: 120,
  duration: 3,
  maxCount: 1,
})

/**
 * 检查服务器连接状态
 */
const checkConnect = () => {
  let isConnected = true
  let _modal
  const heartbeat = () => {
    axios
      .head(`${apiUrlPrefix}/heartbeat`)
      .then(response => {
        if (response.status === 502 && isConnected) {
          isConnected = false
          _modal = modal.warning({
            width: 500,
            title: '系统提示',
            centered: true,
            okButtonProps: {
              style: { display: 'none' },
            },
            content: (
              <div>
                当前服务器可能正在部署，服务暂不可用，建议等待1-2分钟!
                <div className='text-align-center mt20px'>
                  服务器启动状态检测中
                  <LoadingOutlined className='ml10px' />
                </div>
              </div>
            ),
          })
        }
        if (response.status === 200) {
          isConnected = true
          _modal?.destroy()
        }
      })
      .catch(error => {
        console.error('Error fetching data:', error)
      })
  }
  setInterval(heartbeat, 1000 * 5)
}
if (import.meta.env.PROD) {
  checkConnect()
}

// 全局捕获未处理的 Promise.reject
window.addEventListener('unhandledrejection', event => {
  if (event.reason?.message === '关闭Modal' || event.reason?.message === '关闭Drawer') {
    // 阻止默认的错误处理行为
    event.preventDefault()
  }
})

// 1. Initialize
const app = dva({
  // 处理所有请求失败或者异常
  onError: onAppError,
})

window.dvaApp = app

// 增强effects
app.use(dvaEffectsEnhancer(app))

app.use(createLoading({ effects: true }))

// 2. Model 注册全局model
app.model(appModel)
app.model(noticeModel)

// 3. Router
app.router(Router)

// 4. Start
const Start = app.start()

const root = document.getElementById('root')
ReactDOM.createRoot(root).render(
  <ConfigProvider locale={zhCN} theme={theme}>
    <Start />
  </ConfigProvider>,
)
